<template>
  <div class="fileBox" :style="{ width: width + 'px', height: height + 'px' }">
    <div class="upload">
      <div :style="{ fontSize: size + 'px' }">
        <i class="el-icon-plus"></i>
        <span>{{ title }}</span>
        <!-- <span v-show="width != 85">图片尺寸({{`${width} x ${height}`}})</span> -->
      </div>
    </div>
    <input
      :multiple="multiple"
      @change="fileInfo"
      class="fileInput"
      ref="file"
      accept=".png,.jpg"
      type="file"
      value=""
      placeholder="请上传文件"
    />
  </div>
</template>
<script>
export default {
  props: {
    width: {
      type: Number,
      default: 104,
    },
    height: {
      type: Number,
      default: 104,
    },
    size: {
      type: Number,
      default: 12,
    },

    // 是否支持多张上传
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      title: "上传照片",
    };
  },
  methods: {
    // 获取上传后的文件
    async fileInfo(e) {
      // console.log(e.target.files, "eeeeee");
      var format = this.getCaption(e.target.files[0].name); // 获取文件格式
      if (format === "jpg" || format === "png") {
        var files = e.target.files;
        var urls = [];
        var img = document.createElement("img");
        img.src = URL.createObjectURL(files[0]);
        img.onload = () => {
          // console.log(img.naturalWidth, img.naturalHeight, "img");
          if (img.naturalWidth > 72 || img.naturalHeight > 72) {
            this.$message.error("图片尺寸太大了");
            return false;
          }
          urls.push(URL.createObjectURL(files[0]));
          this.$emit("upload", {
            files: e.target.files, // 传给后端的文件
            localUrls: urls, // 本地图片展示
          });
        };
      } else {
        this.$message.error("文件格式错误");
      }

      // this.title = "重新上传";
    },
    // 截取文件是什么类型
    getCaption(obj) {
      var index = obj.lastIndexOf(".");
      obj = obj.substring(index + 1, obj.length);
      return obj;
    },
  },
};
</script>
<style lang="scss" scoped>
.fileBox {
  position: relative;
  border: 1px dashed #ccc;
  cursor: pointer;
  border-radius: 4px;
  &:hover {
    border: 1px dashed #3240ff;
    .upload {
      background-color: #f0f7ff;
      color: #3240ff;
    }
  }
  .fileInput {
    position: absolute;
    top: 0px;
    left: 0px;
    opacity: 0;
    width: 100%;
    height: 100%;
  }
  .upload {
    width: 100%;
    height: 100%;
    text-align: center;
    color: #999;
    background-color: #f5f6fa;
    display: flex;
    justify-content: center;
    align-items: center;

    .el-icon-plus {
      font-size: 24px;
    }
    span {
      display: block;
    }
  }
}
</style>